package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //参数验证
        if (dto.getEquipmentId() == null && (dto.getPhone() == null || dto.getPassword() == null)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Map map = new HashMap();
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //根据手机号获取用户信息
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请输入正确的手机号");
            }
            String password = dto.getPassword();
            String salt = apUser.getSalt();
            String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //判断密码是否正确
            if (md5Password.equals(apUser.getPassword())) {
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("user", apUser);
                map.put("token", token);
                return ResponseResult.okResult(map);
            } else {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }
        //没有输入账号密码
        String token = AppJwtUtil.getToken(0L);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
